<template>
  <Dialog v-model="dialogVisible" title="同意售后" width="500px">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" label-width="120px">
      <!-- 基本信息显示 -->
      <el-form-item label="退款编号：">
        <span>{{ afterSaleData.no }}</span>
      </el-form-item>
      <el-form-item label="商品名称：">
        <span>{{ afterSaleData.spuName }}</span>
      </el-form-item>
      <el-form-item label="原退款金额：">
        <span>{{ fenToYuan(afterSaleData.refundPrice) }} 元</span>
      </el-form-item>

      <!-- 退款方式选择 -->
      <el-form-item label="退款方式：" prop="refundType">
        <el-radio-group v-model="formData.refundType" @change="handleRefundTypeChange">
          <el-radio :label="1">全部退款</el-radio>
          <el-radio :label="2">部分退款</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 部分退款金额输入 -->
      <el-form-item
        v-if="formData.refundType === 2"
        label="退款金额："
        prop="refundPrice"
        :rules="[
          { required: true, message: '请输入退款金额', trigger: 'blur' },
          { validator: validateRefundPrice, trigger: 'blur' }
        ]"
      >
        <el-input-number
          v-model="formData.refundPrice"
          :min="0.01"
          :max="fenToYuan(afterSaleData.refundPrice)"
          :precision="2"
          :step="0.01"
          placeholder="请输入退款金额"
          style="width: 200px"
        >
          <template #append>元</template>
        </el-input-number>
        <div class="text-gray-500 text-sm mt-1">
          最大可退款金额：{{ fenToYuan(afterSaleData.refundPrice) }} 元
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确认退款</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import * as AfterSaleApi from '@/api/mall/trade/afterSale/index'
import { fenToYuan, yuanToFen } from '@/utils'

defineOptions({ name: 'AfterSaleRefundForm' })

const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const afterSaleData = ref<AfterSaleApi.TradeAfterSaleVO>({}) // 售后数据
const formData = reactive({
  refundType: 1, // 退款方式：1-全部退款，2-部分退款
  refundPrice: 0 as number // 退款金额（元）
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (row: AfterSaleApi.TradeAfterSaleVO) => {
  resetForm()
  afterSaleData.value = row
  // 默认显示原退款金额
  formData.refundPrice = Number(fenToYuan(row.refundPrice || 0))
  dialogVisible.value = true
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 退款方式变化处理 */
const handleRefundTypeChange = () => {
  if (formData.refundType === 1) {
    // 全部退款时，设置为原金额
    formData.refundPrice = Number(fenToYuan(afterSaleData.value.refundPrice || 0))
  }
}

/** 验证退款金额 */
const validateRefundPrice = (_rule: any, value: any, callback: any) => {
  if (formData.refundType === 2) {
    const maxAmount = fenToYuan(afterSaleData.value.refundPrice || 0)
    if (!value || value <= 0) {
      callback(new Error('退款金额必须大于0'))
    } else if (value > maxAmount) {
      callback(new Error(`退款金额不能超过 ${maxAmount} 元`))
    } else {
      callback()
    }
  } else {
    callback()
  }
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 表单验证
  if (!formRef.value) return
  const valid = await formRef.value.validate().catch(() => false)
  if (!valid) return

  formLoading.value = true
  try {
    const afterSaleId = afterSaleData.value.id

    // 如果是部分退款，需要先更新退款金额
    if (formData.refundType === 2) {
      // 先调用修改退款金额接口
      const refundPriceFen = yuanToFen(formData.refundPrice || 0)
      await AfterSaleApi.updateRefundPrice({
        id: afterSaleId || null,
        refundPrice: refundPriceFen
      })
    }

    // 调用统一退款接口
    await AfterSaleApi.agreeRefundAfterSale(afterSaleId)

    message.success('退款处理成功')
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success', true)
  } catch (error) {
    console.error('退款处理失败：', error)
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.refundType = 1
  formData.refundPrice = 0
  afterSaleData.value = {}
  formRef.value?.resetFields()
}
</script>

<style scoped>
.text-gray-500 {
  color: #6b7280;
}

.text-sm {
  font-size: 14px;
}

.mt-1 {
  margin-top: 4px;
}
</style>
